package com.example.springbootsecuritydemo.demos.conf;

import com.example.springbootsecuritydemo.demos.filter.ValidateCodeFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;

import javax.sql.DataSource;

@Configuration
public class BrowserSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    ValidateCodeFilter validateCodeFilter;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // http.httpBasic()  // HTTP Basic方式
        // http.formLogin() // 表单方式
        //         .and()
        //         // 授权配置
        //         .authorizeRequests()
        //         // 对login接口进行放行
        //         .anyRequest()  // 所有请求
        //         .authenticated(); // 都需要认证
        // 将验证码 的校验过滤器放在 UsernamePasswordAuthenticationFilter 前面
        http.addFilterBefore(validateCodeFilter, UsernamePasswordAuthenticationFilter.class).
                formLogin() // 表单登录
                // http.httpBasic() // HTTP Basic
                //登录跳转urL
                .loginPage("/authentication/require")
                .loginProcessingUrl("/login")
                .and()
                .authorizeRequests() // 授权配置
                .antMatchers("/authentication/require","/login.html","/code/image").permitAll()
                .anyRequest()  // 所有请求
                .authenticated(); // 都需要认证
        //关闭 跨站请求伪造
        http.csrf().disable();
    }

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }


}